package com.example.datachange.utils;

import com.example.datachange.autoconfigure.DefaultProperties;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 *
 * @author Hao.
 * @version 1.0
 * @since 2022/1/29 15:34
 */
public enum Audio {
    //炸弹爆炸
    BombBlast("bombBlast.wav"),
    COMPLETE("complete.mp3")
    ;

    Audio(String name) {
        this.name = name;
    }

    private String name;

    public String getName() {
        return name;
    }

    public void playMP3() {
        AudioStream as;
        File file = null;
        try {
            final String wavName = name.substring(0, name.lastIndexOf(".")) + System.currentTimeMillis() + ".wav";
            file = new File(DefaultProperties.file.getPath() + wavName);
            AudioUtils.mp3ToWavOfByte(name, wavName);
            Thread.sleep(500);
            InputStream resourceAsStream = new FileInputStream(file);
            as = new AudioStream(resourceAsStream);
            AudioPlayer.player.start(as);
        } catch (Exception e) {
            play(file, 0);
        }
    }

    public void play(File file, int count) {
        InputStream resourceAsStream = null;
        AudioStream as = null;
        try {
            resourceAsStream = new FileInputStream(file);
            as = new AudioStream(resourceAsStream);
            AudioPlayer.player.start(as);
        } catch (Exception e) {
            if (count >= 10) {
                e.printStackTrace();
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            } finally {
                if (Objects.nonNull(as)) {
                    try {
                        as.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                if (Objects.nonNull(resourceAsStream)) {
                    try {
                        resourceAsStream.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
            play(file, ++count);
        }
    }

}
